/*
 * =================================================================
 *
 *            Filename:    TimerId.h
 *
 *         Description:    the wrap class of timer fd;
 *                      
 *             Version:    v1.0   
 *             Created:    2015-11-23 02:40
 *           Reversion:    none
 *            Compiler:    g++
 *            
 *              Author:    wangjin, 836792834@qq.com
 * 
 * ==================================================================
 */

#ifndef TIMERID_H_
#define TIMERID_H_
#include <sys/timerfd.h>
#include <common/comm/Error.h>
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>

class TimerId {
public:
    TimerId( ):timer_fd_(-1)  {
    
    }

    ~TimerId() {
    
    }

    int GenerateTimerFd() {
        timer_fd_ = ::timerfd_create( CLOCK_REALTIME, TFD_NONBLOCK );
        if( timer_fd_ < 0 ) {
            perror("timerfd_create error!\n");
            return FAILED;   
        }

        return SUCCESSFUL;
    }

    int SetIntervalTime( ::timespec start_time, ::timespec interval_time ) {
        ::itimerspec new_value;
        new_value.it_value = start_time;
        new_value.it_interval = interval_time; 

        if ( ::timerfd_settime( timer_fd_ ,0, &new_value, NULL ) < 0 ) {
            perror("timerfd_settime error!\n");
            return FAILED;
        }

        return SUCCESSFUL;
    }

    int GetTime( ::itimerspec &time_value ) {
        if( ::timerfd_gettime( timer_fd_, &time_value ) < 0 ) {
            perror("timerfd_gettime error!\n");
            return FAILED;
        }

        return SUCCESSFUL;
    }

    int ReadTimerCount( uint64_t &timer_count ) {
        return read( timer_fd_, &timer_count, sizeof(uint64_t) );
    }

    int timer_fd() const {
        return timer_fd_;
    }

    int Close() {
        if( timer_fd_ != -1 ) {
            return ::close( timer_fd_ );
        }        

        return 0;
    }

private:
    int timer_fd_; 
};

#endif

